package vm.machine;

import java.util.*;

public class Machine {

    List<Instruction> instructions;

    HashMap<String,Register> registers;

    Stack<Integer> stack;

    public Machine(){
        instructions = new ArrayList<>();
        registers = new HashMap<>();
        stack = new Stack<>();
    }

    public void loadInstructiosn( List<Instruction> instructions){
        this.instructions = instructions;
    }


    public Register getRegister(String name){
        return registers.get(name);
    }

    public Stack<Integer> getStack(){
        return stack;
    }

    public void addRegister(String name,Register register){
        registers.put(name, register);
    }

    public void start() throws InterruptedException {
        while(true){
            Register pc = getRegister("pc");
            Register ax = getRegister("ax");
            if(pc.getValue() == instructions.size()){
                System.out.println("程序执行完毕,结果为:" + ax.getValue());
                break;
            }
            Instruction inst = instructions.get(pc.getValue());
            //打印寄存器和栈数据
            System.out.println(inst.toString());
            inst.exec();
            print();
            Thread.sleep(1000);
        }
    }

    private void print(){
       Set<String> keys = registers.keySet();
       //打印寄存器
        System.out.println("-------------------");
       for(String reg: keys){
           System.out.println(reg + ":" + getRegister(reg).getValue());
       }
       //打印栈
        System.out.println(this.stack);
        System.out.println("-------------------");
    }

}
